<?php
namespace app\admin\controller;

use app\common\model\Message as MessageModel;
use app\common\controller\AdminBase;
use app\common\model\CustomerDetail;
use think\facade\Session;

/**
 * 用户管理
 * Class AdminUser
 * @package app\admin\controller
 */
class Message extends AdminBase
{
    protected $msg_model;

    protected function initialize()
    {
        parent::initialize();
        $this->msg_model = new MessageModel();
    }

    /**
     * 消息列表
     * @param string $keyword
     * @param int    $page
     * @return mixed
     */
    public function index()
    {
        $map = [];
        $data = input();
        if(isset($data['status']) && $data['status'] >= 0){
            $map['status'] = $data['status'];
        }
        $page = input('page') ?? 1;
        $list = $this->msg_model::with("getDetail")->where($map)->order('id DESC')->paginate(15, false, ['page' => $page]);
        return $this->fetch('index', ['list' => $list, 'status' => $data['status'] ?? "-1", 'page' => $page]);
    }


    public function edit($id){
        $msg = $this->msg_model->find($id);
        if($this->request->isPost()){
            $data = $this->request->post();
            $res = $this->msg_model->save($data, ['id' => $id]);
            if($res){
                $this->success('修改成功');
            }else{
                $this->error('修改失败');
            }
        }
//        if($msg['status'] == 0){
//            $msg->status = 1;
//            $msg->save();
//        }

        $msg_list = $msg->getDetailList;

        $msg['content'] = json_decode($msg['content'], true);
        $images = [];
        if(!empty($msg['content']['images'])){
            $images = explodeImg($msg['content']['images']);
        }

        $this->assign('images', $images);
        $this->assign('msg_list', $msg_list);
        return $this->fetch('edit', ['msg' => $msg]);
    }

    //回复
    public function reply(){
        if($this->request->isPost()){
            $data = $this->request->post();

            $data['uid'] = Session::get('admin_id');
            $data['images'] = "";
            $data['status'] = 0;
            $res = CustomerDetail::create($data);
            if($res){
                // 更新消息状态
                $this->msg_model->where('id', $data['customer_id'])->update(['status' => 1]);
                CustomerDetail::where('customer_id', $data['customer_id'])->update(['status' => 1]);
                $this->success('回复成功');
            }else{
                $this->error('回复失败');
            }
        }
    }


    public function close(){
        $id = input('id');
        $this->msg_model->where('id', $id)->update(['status' => 2]);

        $this->success('修改成功','/admin/message');
    }

}